﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Linq;
using INHOADON_TAMVAN.BaoCao;

namespace INHOADON_TAMVAN.Chuc_Nang
{
    public partial class frmThemHoaDon : DevExpress.XtraEditors.XtraForm
    {

        // khai báo 1 hàm delegate
        public delegate void reloadListHD();


        // khởi tạo 1 kiểu hàm delegate
        public reloadListHD reloadList;

        public string id_select;

        public frmThemHoaDon()
        {
            InitializeComponent();
        }
        DataClasses1DataContext db = new DataClasses1DataContext(SystemInfo.pub_ConnString); 
        private void btnClear_Click(object sender, EventArgs e)
        {
            txtSoHoaDon.Text = "";
            
            txtDiachi.Text = "";
            txtDonVi.Text = "";
            txtMasothue.Text = "";
            txtStk.Text = "";
            txtHinhThucThanhToan.Text = "";
            txtThueSuat.Text = "";
        }

        private void frmThemHoaDon_Load(object sender, EventArgs e)
        {
            if (id_select == null)
            {
                deNgay.Text = DateTime.Now.ToString();
                this.luu(false, "load");
                var hanghoa = from hh in db.HangHoas select hh;
                leSanPham.Properties.DataSource = hanghoa;
                leSanPham.Properties.DisplayMember = "HH_Tenhanghoa";
                leSanPham.Properties.ValueMember = "HH_ID";

                lkKhachHang.Properties.DataSource = db.KhachHangs;
                lkKhachHang.Properties.DisplayMember = "KH_HOTEN";
                lkKhachHang.Properties.DisplayMember = "KH_MA";
                lkKhachHang.Properties.ValueMember = "KH_ID";
            }
                //them doi tuong duoc chon
            else
            {
                var hd = db.HoaDons.Single(h=>h.HD_ID == id_select);
                
                    txtDiachi.Text = hd.KhachHang.KH_DIACHI;
                    txtDonVi.Text = hd.KhachHang.KH_DONVI;
                    txtHinhThucThanhToan.Text = hd.HD_Hinhthucthanhtoan;
                    txtThueSuat.Text = hd.HD_Thuesuat.ToString();
                    txtStk.Text = hd.KhachHang.KH_STK.ToString();
                    txtMasothue.Text = hd.KhachHang.KH_MASOTHUE;
                

                deNgay.Text = DateTime.Now.ToString();
                this.luu(false, "load");
                var hanghoa = from hh in db.HangHoas select hh;
                leSanPham.Properties.DataSource = hanghoa;
                leSanPham.Properties.DisplayMember = "HH_Tenhanghoa";
                leSanPham.Properties.ValueMember = "HH_ID";

                
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (txtSoHoaDon.Text == "")
            {
                deSoHoaDon.SetError(txtSoHoaDon, "Vui lòng nhập số hóa đơn!");
            }
            else
            {
                var hoadonC = (from hd in db.HoaDons where hd.HD_ID == txtSoHoaDon.Text select hd).SingleOrDefault();
                if (hoadonC == null)
                {
                    try
                    {
                    //var hoadon = (from hd in db.HoaDons select hd).Single();
                    HoaDon hoadon = new HoaDon();
                    hoadon.HD_ID = txtSoHoaDon.Text;
                    hoadon.KH_ID = Convert.ToInt32(lkKhachHang.EditValue);
                    hoadon.HD_Ngayhd = DateTime.Parse(deNgay.Text);
                    hoadon.HD_Thuesuat = Convert.ToDouble(txtThueSuat.EditValue);
                    hoadon.HD_Hinhthucthanhtoan = txtHinhThucThanhToan.Text;
                    db.HoaDons.InsertOnSubmit(hoadon);
                    db.SubmitChanges();
                    this.reloadList();
                    XtraMessageBox.Show("Thêm hóa đơn thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.luu(true, "save");
                        }
                        catch (Exception ex)
                        {
                            XtraMessageBox.Show("Không thể thêm, đã có lỗi xảy ra vui lòng kiểm tra lại!" + ex.Message.ToString(), "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    else
                    {
                        XtraMessageBox.Show("Hóa đơn này đã có trong danh sách. Vui lòng kiểm tra lại!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
        }

        private void luu(bool check, string flag)
        {
            
            switch(flag) 
            {
                case "load":
                    leSanPham.Enabled = check;
                    txtSoLuong.Enabled = check;
                    btnThemChiTiet.Enabled = check;
                    btnXuatHoaDonGTGT.Enabled = check;
                    txtDonGia.Enabled = check;
                    break;
                case "save":
                    leSanPham.Enabled = check;
                    txtSoLuong.Enabled = check;
                    btnThemChiTiet.Enabled = check;
                    btnXuatHoaDonGTGT.Enabled = check;
                    gcThemHoaDon.Enabled = check;
                    txtDonGia.Enabled = check;

                    txtSoHoaDon.Enabled = false;
                    lkKhachHang.Enabled = false;
                    deNgay.Enabled = false;
                    txtDonVi.Enabled = false;
                    txtDiachi.Enabled = false;
                    txtThueSuat.Enabled = false;
                    txtHinhThucThanhToan.Enabled = false;
                    txtMasothue.Enabled = false;
                    txtStk.Enabled = false;
                    btnSave.Enabled = false;
                    btnClear.Enabled = false;
                    break;
                default:
                    leSanPham.Enabled = check;
                    txtSoLuong.Enabled = check;
                    btnThemChiTiet.Enabled = check;
                    btnXuatHoaDonGTGT.Enabled = check;
                    

                    txtSoHoaDon.Enabled = check;
                    lkKhachHang.Enabled = check;
                    deNgay.Enabled = check;
                    txtDonVi.Enabled = check;
                    txtDiachi.Enabled = check;
                    txtThueSuat.Enabled = check;
                    txtHinhThucThanhToan.Enabled = check;
                    txtMasothue.Enabled = check;
                    txtStk.Enabled = check;
                    break;
            }
        }

        private void btnThemChiTiet_Click(object sender, EventArgs e)
        {
            if (leSanPham.EditValue == null)
            {
                detxtSoluong.SetError(leSanPham, "Vui lòng chọn 1 sản phẩm để thêm chi tiết hóa đơn");
            }
            else if (txtSoLuong.Text == "" || txtSoLuong.Text == "0")
            {
                detxtSoluong.SetError(txtSoLuong, "Xin vui lòng nhập số lượng sản phẩm, và số lượng phải lớn hơn 0");
            }
            else if (txtDonGia.Text == "")
            {
                try
                {
                    var hanghoa = (from hh in db.HangHoas where hh.HH_ID == Int32.Parse(leSanPham.EditValue.ToString()) select hh).Single();
                    Chitiethoadon cthd = new Chitiethoadon();
                    cthd.CTHD_HD_ID = txtSoHoaDon.Text;
                    cthd.CTHD_Soluong = Int32.Parse(txtSoLuong.Text);
                    cthd.CTHD_HH_ID = Int32.Parse(leSanPham.EditValue.ToString());
                    cthd.CTHD_DonGia = hanghoa.HH_Dongia;
                    cthd.CTHD_ThanhTien = Double.Parse(hanghoa.HH_Dongia.ToString()) * Int32.Parse(txtSoLuong.Text);
                    db.Chitiethoadons.InsertOnSubmit(cthd);
                    db.SubmitChanges();
                    this.reloadListCTHD(txtSoHoaDon.Text);
                }
                catch (Exception)
                {
                    XtraMessageBox.Show("Đã có lỗi xảy ra vui lòng kiểm tra lại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

            }
            else
            {
                try
                {
                    var hanghoa = (from hh in db.HangHoas where hh.HH_ID == Int32.Parse(leSanPham.EditValue.ToString()) select hh).Single();
                    Chitiethoadon cthd = new Chitiethoadon();
                    cthd.CTHD_HD_ID = txtSoHoaDon.Text;
                    cthd.CTHD_Soluong = Int32.Parse(txtSoLuong.Text);
                    cthd.CTHD_HH_ID = Int32.Parse(leSanPham.EditValue.ToString());
                    cthd.CTHD_DonGia = Double.Parse(txtDonGia.Text);
                    cthd.CTHD_ThanhTien = Double.Parse(hanghoa.HH_Dongia.ToString()) * Int32.Parse(txtSoLuong.Text);
                    db.Chitiethoadons.InsertOnSubmit(cthd);
                    db.SubmitChanges();
                    this.reloadListCTHD(txtSoHoaDon.Text);
                }
                catch (Exception)
                {
                    XtraMessageBox.Show("Đã có lỗi xảy ra vui lòng kiểm tra lại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

            }
        }

        private void reloadListCTHD(string CTHD_HD_ID)
        {
            var chitiet = from cthd in db.Chitiethoadons join hanghoa in db.HangHoas on cthd.CTHD_HH_ID equals hanghoa.HH_ID where cthd.CTHD_HD_ID == CTHD_HD_ID select new{hanghoa.HH_Tenhanghoa, cthd.CTHD_Soluong, hanghoa.HH_Dongia, cthd.CTHD_ThanhTien, hanghoa.HH_DonViTinh, cthd.CTHD_ID};
            gcThemHoaDon.DataSource = chitiet;
            gcThemHoaDon.RefreshDataSource();
        }

        private void gvThemHoaDon_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.FieldName == "")
            {
                if (e.RowHandle >= 0)
                {
                    e.DisplayText = (e.RowHandle + 1).ToString();
                }
            }
        }

        private void btnXuatHoaDonGTGT_Click(object sender, EventArgs e)
        {
            INHOADON_TAMVAN.BaoCao.frmReportHDGTGT frmReportHDGTGTObj = new INHOADON_TAMVAN.BaoCao.frmReportHDGTGT();
            frmReportHDGTGTObj.reloadList = new frmReportHDGTGT.reloadListHD(this.reloadList);
            frmReportHDGTGTObj.hd_id = txtSoHoaDon.Text;
            frmReportHDGTGTObj.ShowDialog();
            this.Close();
        }

        private void btnDel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }

        private void gvThemHoaDon_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (gvThemHoaDon.RowCount == 0)
                {
                    XtraMessageBox.Show("Vui lòng chọn 1 chi tiết hóa đơn trên danh sách!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    //vị trí chọn trên grid
                    int rowHandles = gvThemHoaDon.FocusedRowHandle;

                    if (rowHandles >= 0)
                    {
                        string id = gvThemHoaDon.GetFocusedRowCellValue(colCTHD_ID).ToString();

                        DialogResult result;
                        result = XtraMessageBox.Show("Bạn có chắc muốn xóa chi tiết hóa đơn này?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (result == DialogResult.Yes)
                        {
                            var ChiTietHoaDon = (from cthd in db.Chitiethoadons where cthd.CTHD_ID == Convert.ToUInt32(id) select cthd).SingleOrDefault();
                            db.Chitiethoadons.DeleteOnSubmit(ChiTietHoaDon);
                            db.SubmitChanges();
                            gvThemHoaDon.DeleteSelectedRows();
                            XtraMessageBox.Show("Xóa chi tiết hóa đơn thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }


                    }
                }
            }
                      
        }

        private void lkKhachHang_EditValueChanged(object sender, EventArgs e)
        {
            var khachhang = db.KhachHangs.Single(t => t.KH_ID == Convert.ToInt32(lkKhachHang.EditValue));
            txtDonVi.Text = khachhang.KH_DONVI.ToString();
            txtMasothue.Text = khachhang.KH_MASOTHUE.ToString();
            txtDiachi.Text = khachhang.KH_DIACHI.ToString();
            txtMasothue.Text = khachhang.KH_MASOTHUE.ToString();
            txtStk.Text = khachhang.KH_STK.ToString();
        }
    }
}